package com.ccm.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.ccm.demo.model.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloController {

	@PostMapping("login")
	public String login(SysUser sysUser){
		JSONObject jsonObject = new JSONObject();
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(sysUser.getSysUsername(), sysUser.getSysPassword());
		try {
			subject.login(usernamePasswordToken);
			jsonObject.put("toke",subject.getSession().getId());
			jsonObject.put("msg","登录成功");
		}catch (IncorrectCredentialsException e) {
			jsonObject.put("msg", "密码错误");
		} catch (LockedAccountException e) {
			jsonObject.put("msg", "登录失败，该用户已被冻结");
		} catch (AuthenticationException e) {
			jsonObject.put("msg", "该用户不存在");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject.toString();
	}

	@RequestMapping(value = "/unauth")
	public Object unauth() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "1000000");
		map.put("msg", "未登录");
		return map;
	}
}
